package vn.com.horoscope.activity;

import vn.com.horoscope.R;
import vn.com.horoscope.common.StaticClass;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.apperhand.device.android.AndroidSDKProvider;
import com.startapp.android.publish.StartAppAd;

public class SplashActivity extends Activity implements Runnable {
	
	private Thread threadSplash;
	private boolean running = true;
	private long timer = 3000;

	private StartAppAd startAppAd = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);		
		
		AndroidSDKProvider.setTestMode(true);
		AndroidSDKProvider.initSDK(this);
	}

	@Override
	public void run() {
		try {
			while (running && timer >= 0) {
				timer -= 100;
				Thread.sleep(100);
			}
		} catch (Exception e) {
			Log.d(StaticClass.tag, "Thread sleep error");
		} finally {
			this.startActivity(new Intent(this, MainActivity.class));
			this.finish();
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			running = false;
		}
		return super.onTouchEvent(event);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (threadSplash == null) {
			threadSplash = new Thread(this);
			threadSplash.start();
		}
		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		finish();
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onPause() {
	   super.onPause(); 
	   if(startAppAd != null) { 
	      boolean showAd = startAppAd.doHome();
	      if (showAd) {
	         startAppAd = null;
	      }
	   } 
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (startAppAd != null){
		       startAppAd.show();
		       startAppAd = null;
		    }
		    super.onBackPressed();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (startAppAd == null) { 
			   startAppAd = new StartAppAd(this);
			   startAppAd.load();
			}
	}
}
